package com.xyy.controller;

import com.xyy.common.Result;
import com.xyy.service.FileService;
import com.xyy.service.DoctorService;
import com.xyy.service.UserService;
import com.xyy.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class FileController {

    @Autowired
    private FileService fileService;
    
    @Autowired
    private DoctorService doctorService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 通用图片上传接口
     * @param file 上传的文件
     * @param type 文件类型（avatar, cover, push_cover）
     * @param request HTTP请求
     * @return 上传结果
     */
    @PostMapping("/image")
    public Result<Map<String, String>> uploadImage(@RequestParam("file") MultipartFile file,
                                                  @RequestParam(value = "type", defaultValue = "avatar") String type,
                                                  HttpServletRequest request) {
        try {
            log.info("收到通用图片上传请求");
            log.info("文件类型: {}", type);
            log.info("文件名: {}", file.getOriginalFilename());
            log.info("文件大小: {} bytes", file.getSize());
            
            // 验证文件
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            
            // 验证文件类型
            if (!fileService.isValidImage(file)) {
                return Result.error("不支持的文件类型，请上传图片文件");
            }
            
            // 验证文件大小（5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return Result.error("文件大小不能超过5MB");
            }
            
            String filePath;
            
            // 根据类型调用不同的上传方法
            switch (type) {
                case "avatar":
                    filePath = fileService.uploadAvatar(file);
                    
                    // 如果是头像上传，需要更新数据库
                    try {
                        // 从token中获取用户ID和类型
                        String token = request.getHeader("Authorization");
                        if (token != null && token.startsWith("Bearer ")) {
                            token = token.substring(7);
                        }
                        
                        if (token != null) {
                            // 尝试解析为医生ID
                            Long doctorId = jwtUtil.getUserIdFromToken(token);
                            if (doctorId != null) {
                                // 检查是否为医生
                                try {
                                    doctorService.updateDoctorAvatar(doctorId, filePath);
                                    log.info("医生头像数据库更新成功，医生ID: {}, 头像路径: {}", doctorId, filePath);
                                } catch (Exception e) {
                                    log.warn("医生头像数据库更新失败，可能不是医生用户: {}", e.getMessage());
                                    
                                    // 尝试作为普通用户更新
                                    try {
                                        Long userId = (Long) request.getAttribute("userId");
                                        if (userId != null) {
                                            userService.updateUserAvatar(userId, filePath);
                                            log.info("用户头像数据库更新成功，用户ID: {}, 头像路径: {}", userId, filePath);
                                        }
                                    } catch (Exception userEx) {
                                        log.warn("用户头像数据库更新也失败: {}", userEx.getMessage());
                                    }
                                }
                            } else {
                                // 尝试从request属性获取用户ID
                                Long userId = (Long) request.getAttribute("userId");
                                if (userId != null) {
                                    userService.updateUserAvatar(userId, filePath);
                                    log.info("用户头像数据库更新成功，用户ID: {}, 头像路径: {}", userId, filePath);
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("头像数据库更新失败: {}", e.getMessage());
                        // 不抛出异常，文件上传成功即可
                    }
                    break;
                case "cover":
                    filePath = fileService.uploadCover(file);
                    break;
                case "push_cover":
                    // 使用活动封面的方法，因为推文封面和活动封面类似
                    filePath = fileService.uploadCover(file);
                    break;
                default:
                    return Result.error("不支持的文件类型: " + type);
            }
            
            // 构建完整的URL
            String serverUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            String fullUrl = serverUrl + "/picture/" + filePath;
            
            Map<String, String> result = new HashMap<>();
            result.put("filePath", filePath);
            result.put("url", fullUrl);
            
            log.info("图片上传成功: {}", filePath);
            log.info("完整URL: {}", fullUrl);
            return Result.success("图片上传成功", result);
            
        } catch (IllegalArgumentException e) {
            log.error("图片上传参数错误", e);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("图片上传失败", e);
            return Result.error("图片上传失败: " + e.getMessage());
        }
    }
}
